package dt.inlee.common.util;

import java.util.Calendar;
import java.util.Locale;

public class MonthSubUtil {
	private static MonthSubUtil msUtil = null;

	private int subNum = 3;

	private int monthNum = 12;

	private MonthSubUtil() {
	}

	public static synchronized MonthSubUtil getInstance() {
		if (msUtil == null)
			msUtil = new MonthSubUtil();
		return msUtil;
	}

	/**
	 * @return int
	 * 
	 *         通过1970差，得出当前分表号（以天为单位）
	 */
	public int getCurrentSub() {
		long l = 1000;
		l = l * 3600 * 24;
		Calendar cNow = Calendar.getInstance();
		Calendar c1970 = Calendar.getInstance();		
		cNow.set(Calendar.HOUR_OF_DAY, 0);
		cNow.set(Calendar.MINUTE, 0);
		cNow.set(Calendar.SECOND, 0);
		c1970.set(Calendar.YEAR, 1970);
		c1970.set(Calendar.MONTH, 0);
		c1970.set(Calendar.DAY_OF_MONTH, 1);
		c1970.set(Calendar.HOUR_OF_DAY, 0);
		c1970.set(Calendar.MINUTE, 0);
		c1970.set(Calendar.SECOND, 0);
		return (int) ((cNow.getTimeInMillis() - c1970.getTimeInMillis()) / l)
				% subNum;
	}

	/**
	 * @param int cur 当前分表号
	 * @return int 得到前1日的分表号
	 * 
	 */
	public int getLastSub(int cur) {
		return cur - 1 >= 0 ? cur - 1 : cur - 1 + subNum;
	}

	/**
	 * @param int cur 当前分表号
	 * @return int 得到后1日的分表号
	 * 
	 */
	public int getNextSub(int cur) {
		return cur + 1 >= subNum ? cur + 1 - subNum : cur + 1;
	}

	/**
	 * @return int 得到当前月号，以0为起点
	 */
	public int getCurrentMon() {
		Calendar thisCal = Calendar.getInstance(Locale.CHINA);
		return thisCal.get(Calendar.MONTH);
	}

	/**
	 * @param int cur 当前月号
	 * @return int 得到上一月的月号，以0为起点
	 */
	public int getLastMon(int cur) {
		return cur - 1 >= 0 ? cur - 1 : cur - 1 + monthNum;
	}

	/**
	 * @param int cur 当前月号
	 * @return int 得到下一月的月号，以0为起点
	 */
	public int getNextMon(int cur) {
		return cur + 1 >= monthNum ? cur + 1 - monthNum : cur + 1;
	}

	public int getMonthNum() {
		return monthNum;
	}

	public void setMonthNum(int monthNum) {
		this.monthNum = monthNum;
	}

	public int getSubNub() {
		return subNum;
	}

	public void setSubNub(int subNub) {
		this.subNum = subNub;
	}

	public static String int2String(int value, int len) {
		String str = Integer.toString(value);
		for (int i = str.length(); i < len; i++) {
			str = "0" + str;
		}
		return str;
	}

	public static void main(String[] strgs) {
		int cur = MonthSubUtil.getInstance().getCurrentMon();
		// System.out.println(MonthSubUtil.int2String(MonthSubUtil.getInstance()
		// .getCurrentMon(), 2));
		// System.out.println(MonthSubUtil.getInstance().getLastMon(cur));
		// System.out.println(MonthSubUtil.getInstance().getNextMon(cur));
		cur = MonthSubUtil.getInstance().getCurrentSub();
		System.out.println(cur);
		// System.out.println(MonthSubUtil.getInstance().getLastSub(cur));
		// System.out.println(MonthSubUtil.getInstance().getNextSub(cur));
	}
}
